using Microsoft.Web.WebView2.Core;
using MultiAgentsShared;
using static MultiAgentsClient.Manager.WorkflowWebviewOperator;

namespace MultiAgentsClient.Presentation.Component;

public sealed partial class WorkflowWebview : UserControl
{
    private readonly IEventBus eventBus;
    private bool isWorkflowLoaded = false;

    public WorkflowWebview()
    {
        InitializeComponent();

        eventBus = EventBus.Instance;

        eventBus.Subscribe<LoadWorkflowCompleteCommand>(cmd => ExecuteJavaScript(cmd.JSCode));
    }

    public void LoadWebviewPage(string path)
    {
        try
        {
            DispatcherQueue.TryEnqueue(async () =>
            {
#pragma warning disable Uno0001
                WorkflowWebviewComponent.WebMessageReceived -= OnWorkflowReceived;
                WorkflowWebviewComponent.WebMessageReceived += OnWorkflowReceived;

                await WorkflowWebviewComponent.EnsureCoreWebView2Async();
                string fullFilePath = Path.GetFullPath(path);
                WorkflowWebviewComponent.NavigationCompleted += (sender, args) =>
                {
                    isWorkflowLoaded = path != "about: blank";
                };

                WorkflowWebviewComponent.Source = new Uri(fullFilePath);
#pragma warning restore Uno0001
            });
        }
        catch (Exception ex)
        {
            Debug.LogError($"Html Error: {ex.Message}");
        }
    }

    private void OnWorkflowReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
    {
        eventBus.Publish(new WorkflowReceiveMessageCommand(sender, e.TryGetWebMessageAsString()));
    }

    public void ExecuteJavaScript(string jsCode)
    {
        try
        {
            DispatcherQueue.TryEnqueue(async () =>
            {
#pragma warning disable Uno0001
                while (!isWorkflowLoaded)
                {
                    await Task.Delay(100);
                }
                await WorkflowWebviewComponent.EnsureCoreWebView2Async();

                await WorkflowWebviewComponent.ExecuteScriptAsync(jsCode);
#pragma warning restore Uno0001
            });
        }
        catch (Exception ex)
        {
            Debug.LogError($"JavaScript Error: {ex.Message}");
        }
    }
}
